
        // 登录状态管理
        let isLoggedIn = false;
        let currentUser = '';
        let userPassword = '';
        
        // 日记数据管理
        let diaryEntries = [];
        
        // 正念练习功能变量
        let isSessionActive = false;
        let sessionTimer = null;
        let currentTime = 0;
        let totalDuration = 600; // 默认10分钟
        let breathPhase = 'inhale'; // inhale, hold, exhale, hold
        
        // 音频相关变量
        let currentAudio = null;
        let isAudioPlaying = false;
        let currentVolume = 50; // 默认音量50%
        let currentSoundType = 'ocean'; // 默认海浪声
        
        // 音频元素映射（已移除冥想音乐）
        const audioElements = {
            rain: document.getElementById('audioRain'),
            ocean: document.getElementById('audioOcean'),
            forest: document.getElementById('audioForest')
        };
        
        // DOM元素
        const loginOverlay = document.getElementById('loginOverlay');
        const changeUsernameOverlay = document.getElementById('changeUsernameOverlay');
        const changePasswordOverlay = document.getElementById('changePasswordOverlay');
        const userMenu = document.getElementById('userMenu');
        const displayUsername = document.getElementById('displayUsername');
        const diaryList = document.getElementById('diaryList');
        const emptyState = document.getElementById('emptyState');
        const startWritingBtn = document.getElementById('startWritingBtn');
        const audioLoading = document.getElementById('audioLoading');
        const volumeIcon = document.getElementById('volumeIcon');
        const volumeSlider = document.getElementById('volumeSlider');
        const backgroundSound = document.getElementById('backgroundSound');
        
        // 显示当前日期
        function setCurrentDate() {
            const now = new Date();
            const options = { year: 'numeric', month: 'long', day: 'numeric', weekday: 'long' };
            document.getElementById('currentDate').textContent = now.toLocaleDateString('zh-CN', options);
        }
        setCurrentDate();

        // 验证登录状态
        function checkLoginStatus() {
            if (!isLoggedIn) {
                loginOverlay.classList.add('show');
                showToast('请先登录后使用', false);
                return false;
            }
            return true;
        }

        // 显示提示框的通用函数
        function showToast(message, isSuccess = true) {
            const toast = document.getElementById('toast');
            const toastMessage = document.getElementById('toastMessage');
            
            toastMessage.textContent = message;
            
            if (isSuccess) {
                toast.classList.remove('error');
                toast.classList.add('success');
                toast.querySelector('span:first-child').className = 'icon-check';
            } else {
                toast.classList.remove('success');
                toast.classList.add('error');
                toast.querySelector('span:first-child').className = 'icon-error';
            }
            
            toast.classList.add('show');
            
            setTimeout(() => {
                toast.classList.remove('show');
            }, 2000);
        }

        // 更新用户信息显示
        function updateUserDisplay() {
            if (isLoggedIn && currentUser) {
                displayUsername.textContent = currentUser;
                userBtn.textContent = currentUser.charAt(0).toUpperCase();
            } else {
                displayUsername.textContent = '用户名';
                userBtn.textContent = '用';
            }
        }

        // 处理登录
        document.getElementById('loginBtn').addEventListener('click', function() {
            const username = document.getElementById('loginUsername').value.trim();
            const password = document.getElementById('loginPassword').value.trim();
            let isValid = true;
            
            // 验证输入
            if (!username) {
                document.getElementById('usernameError').textContent = '请输入用户名';
                isValid = false;
            } else {
                document.getElementById('usernameError').textContent = '';
            }
            
            if (!password) {
                document.getElementById('passwordError').textContent = '请输入密码';
                isValid = false;
            } else {
                document.getElementById('passwordError').textContent = '';
            }
            
            if (!isValid) return;
            
            // 模拟登录验证
            isLoggedIn = true;
            currentUser = username;
            userPassword = password;
            
            // 保存登录状态
            localStorage.setItem('moodDiaryCurrentUser', currentUser);
            localStorage.setItem(`moodDiaryPwd_${currentUser}`, userPassword);
            
            // 加载当前用户的日记数据
            loadDiaryEntries();
            
            // 更新显示
            updateUserDisplay();
            
            // 隐藏登录框
            loginOverlay.classList.remove('show');
            
            // 显示成功提示
            showToast(`登录成功，欢迎回来，${username}！`);
        });

        // 用户按钮点击事件（显示/隐藏用户菜单）
        document.getElementById('userBtn').addEventListener('click', function(e) {
            e.stopPropagation();
            if (isLoggedIn) {
                userMenu.classList.toggle('show');
            } else {
                loginOverlay.classList.add('show');
            }
        });

        // 点击页面其他地方关闭用户菜单
        document.addEventListener('click', function() {
            userMenu.classList.remove('show');
        });

        // 阻止用户菜单内部点击事件冒泡
        userMenu.addEventListener('click', function(e) {
            e.stopPropagation();
        });

        // 修改用户名
        document.getElementById('changeUsernameItem').addEventListener('click', function() {
            userMenu.classList.remove('show');
            document.getElementById('newUsername').value = currentUser;
            document.getElementById('newUsernameError').textContent = '';
            changeUsernameOverlay.classList.add('show');
            document.getElementById('newUsername').focus();
        });

        // 确认修改用户名
        document.getElementById('confirmUsernameBtn').addEventListener('click', function() {
            const newName = document.getElementById('newUsername').value.trim();
            let isValid = true;
            
            if (!newName) {
                document.getElementById('newUsernameError').textContent = '用户名不能为空';
                isValid = false;
            } else if (newName === currentUser) {
                document.getElementById('newUsernameError').textContent = '新用户名与当前用户名相同';
                isValid = false;
            } else {
                document.getElementById('newUsernameError').textContent = '';
            }
            
            if (!isValid) return;
            
            // 获取旧用户名的日记数据
            const oldDiaryData = localStorage.getItem(`moodDiary_${currentUser}`);
            const oldPwdData = localStorage.getItem(`moodDiaryPwd_${currentUser}`);
            
            // 删除旧用户名的日记数据
            localStorage.removeItem(`moodDiary_${currentUser}`);
            localStorage.removeItem(`moodDiaryPwd_${currentUser}`);
            
            // 将日记数据关联到新用户名
            if (oldDiaryData) {
                localStorage.setItem(`moodDiary_${newName}`, oldDiaryData);
            }
            if (oldPwdData) {
                localStorage.setItem(`moodDiaryPwd_${newName}`, oldPwdData);
            }
            
            // 更新用户名
            currentUser = newName;
            localStorage.setItem('moodDiaryCurrentUser', currentUser);
            
            // 更新显示
            updateUserDisplay();
            
            // 隐藏弹窗
            changeUsernameOverlay.classList.remove('show');
            
            // 显示成功提示
            showToast('用户名修改成功');
        });

        // 取消修改用户名
        document.getElementById('cancelUsernameBtn').addEventListener('click', function() {
            changeUsernameOverlay.classList.remove('show');
        });

        // 修改密码
        document.getElementById('changePasswordItem').addEventListener('click', function() {
            userMenu.classList.remove('show');
            // 清空输入框和错误信息
            document.getElementById('oldPassword').value = '';
            document.getElementById('newPassword').value = '';
            document.getElementById('confirmPassword').value = '';
            document.getElementById('oldPasswordError').textContent = '';
            document.getElementById('newPasswordError').textContent = '';
            document.getElementById('confirmPasswordError').textContent = '';
            
            // 显示修改密码弹窗
            changePasswordOverlay.classList.add('show');
            document.getElementById('oldPassword').focus();
        });

        // 确认修改密码
        document.getElementById('confirmPasswordBtn').addEventListener('click', function() {
            const oldPwd = document.getElementById('oldPassword').value.trim();
            const newPwd = document.getElementById('newPassword').value.trim();
            const confirmPwd = document.getElementById('confirmPassword').value.trim();
            let isValid = true;
            
            // 验证原密码
            if (!oldPwd) {
                document.getElementById('oldPasswordError').textContent = '请输入原密码';
                isValid = false;
            } else if (oldPwd !== userPassword) {
                document.getElementById('oldPasswordError').textContent = '原密码不正确';
                isValid = false;
            } else {
                document.getElementById('oldPasswordError').textContent = '';
            }
            
            // 验证新密码
            if (!newPwd) {
                document.getElementById('newPasswordError').textContent = '请输入新密码';
                isValid = false;
            } else if (newPwd.length < 6) {
                document.getElementById('newPasswordError').textContent = '密码长度不能少于6位';
                isValid = false;
            } else if (newPwd === oldPwd) {
                document.getElementById('newPasswordError').textContent = '新密码不能与原密码相同';
                isValid = false;
            } else {
                document.getElementById('newPasswordError').textContent = '';
            }
            
            // 验证确认密码
            if (!confirmPwd) {
                document.getElementById('confirmPasswordError').textContent = '请再次输入新密码';
                isValid = false;
            } else if (confirmPwd !== newPwd) {
                document.getElementById('confirmPasswordError').textContent = '两次输入的密码不一致';
                isValid = false;
            } else {
                document.getElementById('confirmPasswordError').textContent = '';
            }
            
            if (!isValid) return;
            
            // 更新密码
            userPassword = newPwd;
            // 按用户名存储密码
            localStorage.setItem(`moodDiaryPwd_${currentUser}`, userPassword);
            
            // 隐藏弹窗
            changePasswordOverlay.classList.remove('show');
            
            // 显示成功提示
            showToast('密码修改成功，请重新登录');
            
            // 自动退出登录
            setTimeout(() => {
                logout();
            }, 1500);
        });

        // 取消修改密码
        document.getElementById('cancelPasswordBtn').addEventListener('click', function() {
            changePasswordOverlay.classList.remove('show');
        });

        // 退出登录
        function logout() {
            isLoggedIn = false;
            currentUser = '';
            userPassword = '';
            
            // 清除当前用户记录
            localStorage.removeItem('moodDiaryCurrentUser');
            
            // 更新显示
            updateUserDisplay();
            
            // 显示登录框
            loginOverlay.classList.add('show');
            
            // 清空登录表单
            document.getElementById('loginUsername').value = '';
            document.getElementById('loginPassword').value = '';
        }

        // 退出登录按钮点击事件
        document.getElementById('logoutItem').addEventListener('click', function() {
            if (confirm('确定要退出登录吗？')) {
                userMenu.classList.remove('show');
                logout();
                showToast('已退出登录');
            }
        });

        // 情绪选择功能 - 只针对用户可选择的情绪区域
        document.querySelectorAll('#userEmotionSelector .emotion-item').forEach(item => {
            item.addEventListener('click', function() {
                if (!checkLoginStatus()) return;
                
                // 清除同一区域内其他选中状态
                document.querySelectorAll('#userEmotionSelector .emotion-item').forEach(el => {
                    el.classList.remove('selected');
                });
                // 设置当前选中状态
                this.classList.add('selected');
            });
        });

        // 活动标签选择功能
        document.querySelectorAll('.activity-tag').forEach(tag => {
            tag.addEventListener('click', function() {
                if (!checkLoginStatus()) return;
                this.classList.toggle('selected');
            });
        });

        // 语音功能相关
        const voiceBtn = document.getElementById('voiceBtn');
        const voiceAnimation = document.getElementById('voiceAnimation');
        const voiceAnimationIcon = document.getElementById('voiceAnimationIcon');
        const voiceAnimationText = document.getElementById('voiceAnimationText');
        const voiceCancel = document.getElementById('voiceCancel');
        let isRecording = false;
        let recordingSeconds = 0;
        let recordingInterval = null;

        // 更新录音时间显示
        function updateRecordingTime() {
            recordingSeconds++;
            voiceAnimationText.textContent = `正在录音中... ${recordingSeconds}秒`;
            
            // 10秒后自动停止录音
            if (recordingSeconds >= 10) {
                stopRecording(true);
            }
        }

        // 开始录音
        function startRecording() {
            isRecording = true;
            recordingSeconds = 0;
            
            // 更改按钮样式和图标
            voiceBtn.classList.add('recording');
            voiceBtn.className = 'voice-btn icon-stop recording';
            
            // 更新动画界面
            voiceAnimationIcon.className = 'voice-icon icon-stop';
            voiceAnimationText.textContent = '正在录音中... 0秒';
            voiceAnimation.classList.add('show');
            
            // 开始计时
            updateRecordingTime();
            recordingInterval = setInterval(updateRecordingTime, 1000);
        }

        // 停止录音
        function stopRecording(autoStop = false) {
            isRecording = false;
            clearInterval(recordingInterval);
            
            // 恢复按钮样式和图标
            voiceBtn.classList.remove('recording');
            voiceBtn.className = 'voice-btn icon-mic';
            
            // 隐藏动画界面
            voiceAnimation.classList.remove('show');
            voiceAnimationIcon.className = 'voice-icon icon-mic';
            voiceAnimationText.textContent = '点击麦克风开始录音';
            
            if (autoStop || recordingSeconds > 0) {
                // 模拟语音识别结果
                showToast(`录音已完成，时长${recordingSeconds}秒，已转为文字`);
                const moodInput = document.getElementById('moodContent');
                // 模拟语音转文字的结果
                const voiceTexts = [
                    "今天感觉很开心，完成了很多事情。",
                    "天气不错，心情也跟着变好了。",
                    "有点疲惫，但整体还是很充实的一天。",
                    "和朋友聚会很愉快，希望以后常有这样的机会。"
                ];
                const randomText = voiceTexts[Math.floor(Math.random() * voiceTexts.length)];
                moodInput.value += (moodInput.value ? "\n\n" : "") + `${randomText}`;
            }
        }

        // 语音按钮点击事件
        voiceBtn.addEventListener('click', function() {
            if (!checkLoginStatus()) return;
            
            if (isRecording) {
                stopRecording();
            } else {
                startRecording();
            }
        });

        // 取消录音按钮
        voiceCancel.addEventListener('click', function() {
            if (isRecording) {
                isRecording = false;
                clearInterval(recordingInterval);
                
                // 恢复按钮样式
                voiceBtn.classList.remove('recording');
                voiceBtn.className = 'voice-btn icon-mic';
                
                // 隐藏动画
                voiceAnimation.classList.remove('show');
                voiceAnimationText.textContent = '点击麦克风开始录音';
                
                showToast('录音已取消', false);
            } else {
                // 未录音时点击取消，只是关闭面板
                voiceAnimation.classList.remove('show');
            }
        });

        // 保存心情记录功能
        document.getElementById('saveRecordBtn').addEventListener('click', function() {
            if (!checkLoginStatus()) return;
            
            const moodContent = document.getElementById('moodContent').value.trim();
            // 明确指定只获取用户可选择区域的情绪
            const selectedEmotion = document.querySelector('#userEmotionSelector .emotion-item.selected');
            
            // 验证表单数据
            if (!moodContent) {
                showToast('请填写心情内容', false);
                return;
            }
            
            if (!selectedEmotion) {
                showToast('请选择主要情绪', false);
                return;
            }

            // 获取当前日期
            const now = new Date();
            const dateOptions = { year: 'numeric', month: 'long', day: 'numeric', weekday: 'long' };
            const formattedDate = now.toLocaleDateString('zh-CN', dateOptions);
            
            // 获取天气信息
            const weatherIcon = document.querySelector('.weather-icon').outerHTML;
            const weatherInfo = document.getElementById('weatherInfo').textContent;
            const weatherText = weatherInfo.split(' - ')[0];
            
            // 获取选中的活动
            const selectedActivities = Array.from(document.querySelectorAll('.activity-tag.selected'))
                .map(tag => tag.textContent);
            
            // 获取笔记内容
            const dailyNotes = document.getElementById('dailyNotes').value.trim();
            
            // 创建日记对象
            const newEntry = {
                id: Date.now(), // 使用时间戳作为唯一ID
                date: formattedDate,
                timestamp: now.getTime(), // 存储时间戳用于筛选
                weather: weatherText,
                weatherIcon: weatherIcon,
                content: moodContent,
                emotion: selectedEmotion.textContent,
                emotionClass: selectedEmotion.className.split(' ')[1],
                activities: selectedActivities,
                notes: dailyNotes
            };
            
            // 添加到日记列表
            diaryEntries.unshift(newEntry); // 添加到数组开头
            
            // 保存到本地存储（按用户名区分）
            saveDiaryEntries();
            
            // 刷新日记列表显示
            renderDiaryEntries();

            // 显示成功提示
            showToast('今日心情记录已保存并添加到日记！');

            // 清空表单
            document.getElementById('moodContent').value = '';
            document.getElementById('dailyNotes').value = '';
            document.querySelectorAll('.activity-tag.selected').forEach(tag => {
                tag.classList.remove('selected');
            });
            document.querySelectorAll('#userEmotionSelector .emotion-item.selected').forEach(el => {
                el.classList.remove('selected');
            });

            // 切换到日记页面
            setTimeout(() => {
                document.querySelector('.sidebar-item.icon-diary').click();
            }, 2000);
        });

        // 页面切换功能
        document.querySelectorAll('.sidebar-item').forEach(item => {
            item.addEventListener('click', function() {
                if (!checkLoginStatus()) return;
                
                document.querySelectorAll('.sidebar-item').forEach(i => i.classList.remove('active'));
                document.querySelectorAll('.page-content').forEach(page => page.classList.remove('active'));
                
                this.classList.add('active');
                const pageId = this.getAttribute('data-page');
                document.querySelector(`.${pageId}-page`).classList.add('active');
                
                // 如果切换到日记页面，刷新日记列表
                if (pageId === 'diary') {
                    renderDiaryEntries();
                }
                
                // 如果离开正念练习页面，停止音频
                if (pageId !== 'mindfulness' && document.querySelector('.mindfulness-session-page').classList.contains('active')) {
                    stopAllAudio();
                }
            });
        });

        // 开始记录按钮点击事件
        startWritingBtn.addEventListener('click', function() {
            document.querySelector('.sidebar-item.icon-home').click();
            document.getElementById('moodContent').focus();
        });

        // 筛选按钮功能
        function initFilterButtons() {
            // 获取所有筛选按钮
            const filterButtons = document.querySelectorAll('.diary-filters .filter-btn');
            
            // 为每个按钮添加点击事件监听器
            filterButtons.forEach(btn => {
                btn.addEventListener('click', function() {
                    if (!checkLoginStatus()) return;
                    
                    // 更新按钮状态
                    filterButtons.forEach(b => b.classList.remove('active'));
                    this.classList.add('active');
                    
                    // 添加按钮点击效果
                    this.classList.add('filter-transition');
                    this.style.transform = 'scale(0.95)';
                    setTimeout(() => {
                        this.style.transform = 'scale(1)';
                    }, 200);
                    
                    // 获取筛选类型
                    const filterType = this.getAttribute('data-filter');
                    
                    // 筛选并显示日记
                    filterAndShowDiaries(filterType);
                    
                    // 显示筛选提示
                    let filterText = '';
                    switch(filterType) {
                        case 'week': filterText = '本周'; break;
                        case 'month': filterText = '本月'; break;
                        case 'year': filterText = '今年'; break;
                        case 'all': filterText = '全部'; break;
                    }
                    showToast(`已显示${filterText}的日记记录`);
                });
            });
        }

        // 筛选并显示日记
        function filterAndShowDiaries(filterType) {
            const now = new Date();
            const currentTime = now.getTime();
            
            // 计算时间范围（毫秒）
            let timeRange = 0;
            
            switch(filterType) {
                case 'week':
                    // 一周的毫秒数：7 * 24 * 60 * 60 * 1000 = 604800000
                    timeRange = 604800000;
                    break;
                case 'month':
                    // 一个月的毫秒数（近似30天）
                    timeRange = 30 * 24 * 60 * 60 * 1000;
                    break;
                case 'year':
                    // 一年的毫秒数（近似365天）
                    timeRange = 365 * 24 * 60 * 60 * 1000;
                    break;
                case 'all':
                default:
                    // 不筛选
                    timeRange = 0;
                    break;
            }
            
            // 计算起始时间戳
            const startTimestamp = timeRange > 0 ? currentTime - timeRange : 0;
            
            // 获取当前所有日记项并添加淡出动画
            const currentItems = document.querySelectorAll('.diary-item');
            currentItems.forEach((item, index) => {
                // 错开时间淡出，创建流畅动画
                setTimeout(() => {
                    item.style.opacity = '0';
                    item.style.transform = 'translateY(10px)';
                }, index * 50);
            });
            
            // 短暂延迟后执行筛选，等待淡出动画完成
            setTimeout(() => {
                // 筛选日记
                const filteredEntries = diaryEntries.filter(entry => entry.timestamp >= startTimestamp);
                
                // 更新显示
                updateDiaryDisplay(filteredEntries);
            }, currentItems.length * 50 + 200);
        }

        // 更新日记显示
        function updateDiaryDisplay(entries) {
            // 清空当前列表
            diaryList.innerHTML = '';
            
            // 检查是否有日记
            if (entries.length === 0) {
                // 显示空状态，添加淡入动画
                emptyState.classList.remove('hidden');
                emptyState.classList.add('show');
                return;
            }
            
            // 隐藏空状态
            emptyState.classList.remove('show');
            emptyState.classList.add('hidden');
            
            // 添加日记项，带渐入动画
            entries.forEach((entry, index) => {
                const diaryItem = createDiaryElement(entry);
                // 初始状态设为透明和偏移
                diaryItem.style.opacity = '0';
                diaryItem.style.transform = 'translateY(10px)';
                diaryList.appendChild(diaryItem);
                
                // 逐个显示，创建顺序动画效果
                setTimeout(() => {
                    diaryItem.style.opacity = '1';
                    diaryItem.style.transform = 'translateY(0)';
                }, 100 * index);
            });
        }

        // 创建日记元素
        function createDiaryElement(entry) {
            const diaryItem = document.createElement('div');
            diaryItem.className = 'diary-item';
            diaryItem.setAttribute('data-id', entry.id);
            
            diaryItem.innerHTML = `
                <div class="diary-header">
                    <div class="diary-date">${entry.date}</div>
                    <div class="diary-weather">${entry.weatherIcon} ${entry.weather}</div>
                </div>
                <div class="diary-content">${entry.content}</div>
                <div class="diary-activities">
                    ${entry.activities.map(activity => 
                        `<span class="activity-badge">${activity}</span>`
                    ).join('')}
                </div>
                ${entry.notes ? `<div class="diary-notes"><strong>思考与计划：</strong>${entry.notes}</div>` : ''}
                <div class="diary-emotion ${entry.emotionClass}">${entry.emotion}</div>
            `;
            
            return diaryItem;
        }

        // 渲染所有日记
        function renderDiaryEntries() {
            // 检查当前激活的筛选按钮
            const activeFilter = document.querySelector('.diary-filters .filter-btn.active');
            const filterType = activeFilter ? activeFilter.getAttribute('data-filter') : 'all';
            
            // 应用筛选
            filterAndShowDiaries(filterType);
        }

        // 保存日记到本地存储（按用户名区分）
        function saveDiaryEntries() {
            if (currentUser) {
                try {
                    localStorage.setItem(`moodDiary_${currentUser}`, JSON.stringify(diaryEntries));
                    console.log('日记保存成功:', diaryEntries);
                } catch (e) {
                    console.error('保存日记失败:', e);
                    showToast('保存失败，请稍后再试', false);
                }
            }
        }

        // 从本地存储加载日记（按用户名区分）
        function loadDiaryEntries() {
            diaryEntries = [];
            
            if (currentUser) {
                try {
                    const savedEntries = localStorage.getItem(`moodDiary_${currentUser}`);
                    if (savedEntries) {
                        diaryEntries = JSON.parse(savedEntries);
                        console.log('日记加载成功:', diaryEntries);
                    }
                } catch (e) {
                    console.error('加载日记失败:', e);
                    diaryEntries = [];
                }
            }
            
            // 渲染日记
            renderDiaryEntries();
        }

        // 添加日记按钮
        document.querySelector('.add-diary-btn').addEventListener('click', function() {
            if (!checkLoginStatus()) return;
            
            document.querySelector('.sidebar-item.icon-home').click();
            document.getElementById('moodContent').focus();
        });

        // 音频控制函数
        function playSelectedAudio() {
            // 先停止当前播放的音频
            stopAllAudio();
            
            if (currentSoundType === 'none') {
                isAudioPlaying = false;
                return;
            }
            
            // 获取要播放的音频元素
            currentAudio = audioElements[currentSoundType];
            if (!currentAudio) return;
            
            // 显示加载状态
            audioLoading.classList.add('show');
            
            // 尝试播放音频
            currentAudio.play()
                .then(() => {
                    isAudioPlaying = true;
                    audioLoading.classList.remove('show');
                    updateVolumeIcon();
                    console.log(`播放${currentSoundType}音频`);
                })
                .catch(error => {
                    isAudioPlaying = false;
                    audioLoading.classList.remove('show');
                    console.error('音频播放失败:', error);
                    
                    // 根据错误类型显示不同提示
                    if (error.name === 'NotAllowedError') {
                        showToast('请先点击开始练习按钮以播放音频', false);
                    } else {
                        showToast(`音频播放失败: ${error.message}`, false);
                    }
                });
        }

        function pauseCurrentAudio() {
            if (currentAudio && isAudioPlaying) {
                currentAudio.pause();
                isAudioPlaying = false;
            }
        }

        function resumeCurrentAudio() {
            if (currentAudio && !isAudioPlaying && currentSoundType !== 'none') {
                currentAudio.play()
                    .then(() => {
                        isAudioPlaying = true;
                    })
                    .catch(error => {
                        console.error('恢复音频播放失败:', error);
                    });
            }
        }

        function stopAllAudio() {
            Object.values(audioElements).forEach(audio => {
                audio.pause();
                audio.currentTime = 0; // 重置到开始位置
            });
            isAudioPlaying = false;
        }

        function setVolume(volume) {
            currentVolume = volume;
            Object.values(audioElements).forEach(audio => {
                audio.volume = currentVolume / 100;
            });
            updateVolumeIcon();
            // 保存音量设置
            localStorage.setItem('audioVolume', currentVolume);
        }

        function toggleMute() {
            if (currentVolume > 0) {
                // 保存当前音量并静音
                localStorage.setItem('lastAudioVolume', currentVolume);
                setVolume(0);
                volumeSlider.value = 0;
            } else {
                // 恢复之前的音量
                const lastVolume = localStorage.getItem('lastAudioVolume') || 50;
                setVolume(parseInt(lastVolume));
                volumeSlider.value = lastVolume;
            }
        }

        function updateVolumeIcon() {
            if (currentVolume === 0) {
                volumeIcon.className = 'volume-icon icon-volume-off';
            } else if (currentVolume < 30) {
                volumeIcon.className = 'volume-icon icon-volume-low';
            } else if (currentVolume < 70) {
                volumeIcon.className = 'volume-icon icon-volume-medium';
            } else {
                volumeIcon.className = 'volume-icon icon-volume-high';
            }
        }

        function getAudioErrorText(errorCode) {
            switch(errorCode) {
                case MediaError.MEDIA_ERR_ABORTED:
                    return "音频加载被中止";
                case MediaError.MEDIA_ERR_NETWORK:
                    return "网络错误导致音频加载失败";
                case MediaError.MEDIA_ERR_DECODE:
                    return "音频解码失败";
                case MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED:
                    return "音频格式不支持";
                default:
                    return "未知错误";
            }
        }

        // 初始化正念练习功能
        function initMindfulnessSession() {
            // 初始化音频设置
            function initAudioSettings() {
                // 设置所有音频的初始音量和循环播放
                Object.values(audioElements).forEach(audio => {
                    audio.volume = currentVolume / 100;
                    audio.loop = true;
                    
                    // 音频加载事件
                    audio.addEventListener('loadstart', () => {
                        audioLoading.classList.add('show');
                    });
                    
                    audio.addEventListener('canplay', () => {
                        audioLoading.classList.remove('show');
                    });
                    
                    audio.addEventListener('error', (e) => {
                        audioLoading.classList.remove('show');
                        showToast(`音频加载失败: ${getAudioErrorText(e.target.error.code)}`, false);
                    });
                });
                
                // 音量滑块事件
                volumeSlider.addEventListener('input', function() {
                    setVolume(parseInt(this.value));
                });
                
                // 音量图标点击事件（静音切换）
                volumeIcon.addEventListener('click', toggleMute);
                
                // 背景声音选择事件
                backgroundSound.addEventListener('change', function() {
                    const newSoundType = this.value;
                    if (isAudioPlaying || currentSoundType !== newSoundType) {
                        currentSoundType = newSoundType;
                        if (isAudioPlaying) {
                            playSelectedAudio();
                        }
                    }
                });
            }
            
            // 呼吸动画功能
            function animateBreath() {
                if (!isSessionActive) return;
                
                const outerCircle = document.querySelector('.breath-circle');
                const innerCircle = document.querySelector('.breath-inner-circle');
                const instruction = document.getElementById('breathInstruction');
                
                // 根据呼吸节奏设置时间（秒）
                const rhythm = document.getElementById('breathRhythm').value.split('-').map(Number);
                const [inhaleTime, hold1Time, exhaleTime, hold2Time] = rhythm.length === 4 ? rhythm : [...rhythm, 0];
                
                if (breathPhase === 'inhale') {
                    // 吸气阶段
                    outerCircle.style.transform = 'scale(1.2)';
                    innerCircle.style.transform = 'scale(1.2)';
                    instruction.textContent = '吸气...';
                    breathPhase = hold1Time > 0 ? 'hold' : 'exhale';
                    
                    setTimeout(animateBreath, inhaleTime * 1000);
                } else if (breathPhase === 'hold') {
                    // 吸气后屏息
                    instruction.textContent = '保持...';
                    breathPhase = 'exhale';
                    
                    setTimeout(animateBreath, hold1Time * 1000);
                } else if (breathPhase === 'exhale') {
                    // 呼气阶段
                    outerCircle.style.transform = 'scale(1)';
                    innerCircle.style.transform = 'scale(1)';
                    instruction.textContent = '呼气...';
                    breathPhase = hold2Time > 0 ? 'hold2' : 'inhale';
                    
                    setTimeout(animateBreath, exhaleTime * 1000);
                } else if (breathPhase === 'hold2') {
                    // 呼气后屏息
                    instruction.textContent = '保持...';
                    breathPhase = 'inhale';
                    
                    setTimeout(animateBreath, hold2Time * 1000);
                }
            }
            
            // 更新计时器显示
            function updateTimer() {
                currentTime++;
                
                const minutes = Math.floor(currentTime / 60).toString().padStart(2, '0');
                const seconds = (currentTime % 60).toString().padStart(2, '0');
                document.getElementById('sessionTimer').textContent = `${minutes}:${seconds}`;
                
                // 检查是否完成
                if (currentTime >= totalDuration) {
                    endSession(true);
                }
            }
            
            // 开始练习
            document.getElementById('startSessionBtn').addEventListener('click', function() {
                if (!isSessionActive) {
                    isSessionActive = true;
                    this.disabled = true;
                    document.getElementById('pauseSessionBtn').disabled = false;
                    
                    // 获取设置的时长
                    totalDuration = parseInt(document.getElementById('sessionDuration').value);
                    
                    // 开始计时
                    sessionTimer = setInterval(updateTimer, 1000);
                    
                    // 开始呼吸动画
                    animateBreath();
                    
                    // 播放背景声音
                    currentSoundType = backgroundSound.value;
                    playSelectedAudio();
                    
                    showToast('正念练习已开始');
                }
            });
            
            // 暂停练习
            document.getElementById('pauseSessionBtn').addEventListener('click', function() {
                if (isSessionActive) {
                    // 暂停状态
                    clearInterval(sessionTimer);
                    isSessionActive = false;
                    this.textContent = '继续';
                    document.getElementById('startSessionBtn').disabled = false;
                    
                    // 暂停背景音
                    pauseCurrentAudio();
                    
                    showToast('练习已暂停');
                } else {
                    // 继续状态
                    isSessionActive = true;
                    this.textContent = '暂停';
                    document.getElementById('startSessionBtn').disabled = true;
                    
                    sessionTimer = setInterval(updateTimer, 1000);
                    animateBreath();
                    
                    // 恢复背景音
                    resumeCurrentAudio();
                    
                    showToast('练习已继续');
                }
            });
            
            // 结束练习
            document.getElementById('endSessionBtn').addEventListener('click', function() {
                if (isSessionActive || currentTime > 0) {
                    if (confirm('确定要结束当前练习吗？')) {
                        endSession(false);
                    }
                }
            });
            
            // 关闭练习完成模态框
            document.getElementById('closeSessionBtn').addEventListener('click', function() {
                document.getElementById('sessionCompleteOverlay').classList.remove('show');
                document.querySelector('.sidebar-item.icon-mindfulness').click();
                showToast('感谢完成正念练习');
            });
            
            // 再练习一次
            document.getElementById('anotherSessionBtn').addEventListener('click', function() {
                document.getElementById('sessionCompleteOverlay').classList.remove('show');
                resetSession();
                showToast('准备开始新的练习');
            });
            
            // 重置练习
            function resetSession() {
                clearInterval(sessionTimer);
                isSessionActive = false;
                currentTime = 0;
                breathPhase = 'inhale';
                
                // 停止背景音
                stopAllAudio();
                
                document.getElementById('sessionTimer').textContent = '00:00';
                document.getElementById('startSessionBtn').disabled = false;
                document.getElementById('pauseSessionBtn').disabled = true;
                document.getElementById('pauseSessionBtn').textContent = '暂停';
                
                // 重置圆圈大小
                document.querySelector('.breath-circle').style.transform = 'scale(1)';
                document.querySelector('.breath-inner-circle').style.transform = 'scale(1)';
                document.getElementById('breathInstruction').textContent = '准备开始';
            }
            
            // 结束练习处理
            function endSession(isComplete) {
                clearInterval(sessionTimer);
                isSessionActive = false;
                
                // 停止背景音
                stopAllAudio();
                
                if (isComplete) {
                    // 练习完成
                    const minutes = Math.floor(totalDuration / 60);
                    document.getElementById('completedDuration').textContent = minutes;
                    document.getElementById('sessionCompleteOverlay').classList.add('show');
                } else {
                    // 手动结束
                    resetSession();
                    showToast('练习已结束');
                }
            }
            
            // 切换练习类型
            function changeSessionType(title, description) {
                document.getElementById('sessionTitle').textContent = title;
                document.getElementById('sessionDescription').textContent = description;
                resetSession();
            }
            
            // 为正念练习卡片添加点击事件
            document.querySelectorAll('.mindfulness-exercise-btn').forEach((btn, index) => {
                btn.addEventListener('click', function() {
                    if (!checkLoginStatus()) return;
                    
                    const exercises = [
                        {
                            title: '呼吸练习',
                            description: '跟随动画进行深呼吸。当圆圈扩大时吸气，缩小时呼气。专注于你的呼吸，感受身体的变化。'
                        },
                        {
                            title: '身体扫描',
                            description: '从脚趾开始，逐渐将注意力移向全身各个部位。感受身体的感觉，不需要改变它，只是觉察它。'
                        },
                        {
                            title: '正念冥想',
                            description: '将注意力集中在呼吸上，当思绪wandering时，温和地将注意力带回呼吸。培养当下的觉察力。'
                        }
                    ];
                    
                    // 更新侧边栏选中状态
                    document.querySelectorAll('.sidebar-item').forEach(i => i.classList.remove('active'));
                    document.querySelector('.sidebar-item.icon-mindfulness').classList.add('active');
                    
                    // 切换到练习页面
                    document.querySelectorAll('.page-content').forEach(page => page.classList.remove('active'));
                    document.querySelector('.mindfulness-session-page').classList.add('active');
                    
                    // 更新练习内容
                    changeSessionType(exercises[index].title, exercises[index].description);
                });
            });
            
            // 初始化音频设置
            initAudioSettings();
        }

        // 页面加载时初始化
        window.addEventListener('load', function() {
            // 初始化筛选按钮
            initFilterButtons();
            
            // 初始化正念练习功能
            initMindfulnessSession();
            
            // 加载保存的音量设置
            const savedVolume = localStorage.getItem('audioVolume');
            if (savedVolume) {
                currentVolume = parseInt(savedVolume);
                volumeSlider.value = currentVolume;
                updateVolumeIcon();
            }
            
            // 检查本地存储中的当前登录用户
            const savedUser = localStorage.getItem('moodDiaryCurrentUser');
            
            if (savedUser) {
                // 获取该用户的密码
                const savedPwd = localStorage.getItem(`moodDiaryPwd_${savedUser}`);
                
                if (savedPwd) {
                    isLoggedIn = true;
                    currentUser = savedUser;
                    userPassword = savedPwd;
                    updateUserDisplay();
                    loadDiaryEntries();
                } else {
                    // 密码不存在，需要重新登录
                    loginOverlay.classList.add('show');
                }
            } else {
                // 未登录状态下显示登录框
                loginOverlay.classList.add('show');
            }
        });